package LC160;

import java.util.List;

public class Solution2 {
    //长度对齐
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {

        if(headA==null||headB==null){
            return null;
        }

        int lengthA=getListLength(headA);
        int lengthB=getListLength(headB);
        if(lengthA>lengthB){
            headA=newHead(headA,lengthA-lengthB);
        }else{
            headB=newHead(headB,lengthB-lengthA);
        }

        while(headA!=null&&headB!=null){
            if(headA==headB){
                return headA;
            }
            headA=headA.next;
            headB=headB.next;
        }
        return null;
    }

    private int getListLength(ListNode head){
        int length=0;
        while(head!=null){
            length++;
            head=head.next;
        }
        return length;
    }

    private ListNode newHead(ListNode head,int step){
        for(int i=0;i<step;i++){
            if(head!=null){
                head=head.next;
            }
        }
        return head;
    }

}
